//
//  CWQ_historySearchVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/9/13.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "CWQ_SearchVC.h"
#import "CWQ_HistoryLearnCell.h"
#import "CWQ_searchView.h"
#import "YYHeaderView.h"
#import "BTCourseModel.H"
#import "UIViewController+BackButtonHandler.h"
#import "CWQ_courseIntroductionCell.h"
#import "BTCourseDetailVC.h"
#import "BTTopicListModel.h"
#import "BTTopicDetailVC.h"
#import "BTHistorySearchM.h"
#import "BTCosultModel.h"
#import "BTConsultCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "BTBaseWebVC.h"
#import "Masonry.h"
static NSString * const cellId = @"CWQ_HistoryLearnCellID";
@interface CWQ_SearchVC ()<UITextFieldDelegate, UIAlertViewDelegate>{

CWQ_searchView * searchView;
}
@property(nonatomic, copy)NSString *searchWords;
@property (nonatomic,  assign) CWQ_historySearchVCType searchType;





@end

@implementation CWQ_SearchVC

- (instancetype)initWithSearchWords:(NSString *)searchWords withType:(CWQ_historySearchVCType)type {
    if (self = [super init]) {
        _searchWords = searchWords;
        _searchType = type;
    }
    return self;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CWQ_courseIntroductionCell" bundle:nil] forCellReuseIdentifier:@"CWQ_courseIntroductionCell"];
    weakSelf_define;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).with.offset(0);
        make.right.equalTo(weakSelf.view).with.offset(0);
        make.top.equalTo(weakSelf.view).with.offset(0);
        make.bottom.equalTo(weakSelf.view).with.offset(0);
    }];
    [self setupSearchView];
    // Do any additional setup after loading the view.
   
    [self.tableView wsj_HeaderRefreshBlock:^{
         [weakSelf requestMarketCourseList:YES];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
         [weakSelf requestMarketCourseList:NO];
    }];
    [weakSelf.tableView.header beginRefreshing];
   
}
- (void)requestMarketCourseList:(BOOL)isRecover{
  
    static NSInteger  page =1;
   
    if (isRecover) {
        page = 1;
    }else{
        page ++;
        
    }
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    params[@"page"] = @(page);
    params[@"rows"] = @(10);
    if (!_searchWords) {
        alertMessage(@"请输入关键字...");
    }
 
    NSString *url;
    if (_searchType == CWQ_historySearchVCType_Course_ShangXueyuan) {
          url = kSearchCourseInShangXueyuan;
          params[@"courseName"] = _searchWords;;
    }
    if (_searchType == CWQ_historySearchVCType_Course_Market) {

        params[@"courseName"] = _searchWords;;
        url = kSearchCourseInMarket;
    }
  
   
    if (_searchType == CWQ_historySearchVCType_Course_FlagSale) {
         params[@"id"] =@(self.flagId);
        params[@"name"] = _searchWords;;
        url  = kMarketFlagsOrMarketCourseList;;
    }
    if (_searchType == CWQ_historySearchVCType_Course_Sale_all) {
      
        params[@"courseName"] = _searchWords;;
        url  = kSearchCourseInSale;;
    }
    if (self.searchType == CWQ_historySearchVCType_Topic) {
        params[@"name"] = _searchWords;
        url = kTopicList;
    }
    if (self.searchType == CWQ_historySearchVCType_Course_Guanli) {
         params[@"courseName"] = _searchWords;
        url = kSearchCourseInGuanliXiueyuan;
    }
    if (self.searchType == CWQ_historySearchVCType_Course_FlagGuanli) {
        params[@"name"] = _searchWords;
        params[@"id"] = @(self.flagId);
        url = kSaleCourseList;
    }
    if (self.searchType == CWQ_historySearchVCType_Consult) {
        params[@"subjectName"] = _searchWords;
        url = kConsultsList;
    }
    
    weakSelf_define;
    self.tableView.loading = YES;
    [[BTNetworkManager sharedMg] POST:url parameters:params success:^(NSDictionary *responseObject) {
        weakSelf.tableView.loading = NO;
       
        [weakSelf.tableView.header endRefreshing];
  //--------------------------------- 咨询的返回数据是大鹏的写,妈的解析特别-------
        if (weakSelf.searchType == CWQ_historySearchVCType_Consult) {
            
            NSInteger totalPage;
            
            if ([responseObject[@"totalPage"] isKindOfClass:[NSNull class]] ) {
                totalPage = 0;
            }else{
                totalPage = [responseObject[@"totalPage"] integerValue];;
            }
            NSInteger currentPage = [responseObject[@"page"] integerValue];
            
            
            if (currentPage >=totalPage) {
                [weakSelf.tableView.footer noticeNoMoreData];
                
            }else{
                [weakSelf.tableView.footer resetNoMoreData];
                
            }

            if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                NSArray *dataArray = responseObject[@"data"];
                if (isRecover) {
                    [weakSelf.dataArray removeAllObjects];
                    
                }
                [weakSelf.dataArray addObjectsFromArray:[BTCosultModel mj_objectArrayWithKeyValuesArray:dataArray]];
            
           }
            
            [weakSelf.tableView reloadData];
            return ;
        }
        
        
  //------------------------其余---------------
        
        NSInteger totalPage;
        
        if ([responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]] ) {
            totalPage = 0;
        }else{
            totalPage = [responseObject[@"data"][@"totalPage"] integerValue];;
        }
        
        //                总条数
        NSInteger currentPage = [responseObject[@"data"][@"page"] integerValue];
        
        
        if (currentPage >=totalPage) {
            [weakSelf.tableView.footer noticeNoMoreData];
            
        }else{
            [weakSelf.tableView.footer resetNoMoreData];
            
        }

        if (responseObject_Err) {
            return ;
        }
        
        if (weakSelf.searchType == CWQ_historySearchVCType_Course_ShangXueyuan || weakSelf.searchType == CWQ_historySearchVCType_Course_Guanli ||
            weakSelf.searchType == CWQ_historySearchVCType_Course_Market ||
            weakSelf.searchType == CWQ_historySearchVCType_Course_Sale_all ||
            weakSelf.searchType == CWQ_historySearchVCType_Course_Guanli ||
             weakSelf.searchType == CWQ_historySearchVCType_Course_FlagGuanli
            ) {
            if (responseObject_success) {
                if ([responseObject[@"data"][@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *dataArray = responseObject[@"data"][@"data"];
                    if (isRecover) {
                        [weakSelf.dataArray removeAllObjects];
                        
                    }
                    [weakSelf.dataArray addObjectsFromArray:[BTCourseModel mj_objectArrayWithKeyValuesArray:dataArray]];
                    
                }
            }
        }
        
        if (weakSelf.searchType == CWQ_historySearchVCType_Course_FlagSale ) {
            if ([responseObject[@"data"][@"courseList"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict =responseObject[@"data"][@"courseList"] ;
                if ([dict[@"data"] isKindOfClass:[NSArray class]]) {
                    
                    if (isRecover) {
                        [weakSelf.dataArray removeAllObjects];
                        
                    }
                    
                    [weakSelf.dataArray addObjectsFromArray:[BTCourseModel mj_objectArrayWithKeyValuesArray:dict[@"data"]]];
           
                }
                
            }
            
        }
        
        if (weakSelf.searchType == CWQ_historySearchVCType_Topic) {
            if (responseObject_success) {
                if ([responseObject[@"data"][@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *dataArray = responseObject[@"data"][@"data"];
                    if (isRecover) {
                        [weakSelf.dataArray removeAllObjects];
                        
                    }
                    [weakSelf.dataArray addObjectsFromArray:[BTTopicListModel mj_objectArrayWithKeyValuesArray:dataArray]];
                    
                }

            }
            
            
        }
        
        if (weakSelf.searchType == CWQ_historySearchVCType_Course_Guanli) {
            
        }
       
        
        [weakSelf.tableView reloadData];
        
        
    } failure:^(NSString *err) {
        weakSelf.tableView.loading = NO;
        [weakSelf.tableView.header endRefreshing];
    }];
    
    
}


-(void)setupSearchView
{
    searchView = [CWQ_searchView creatView];
    
    searchView.frame = CGRectMake(0, 0, kScreenWidth, 40);
  
    weakSelf_define;
    [searchView setCWQGetTitle:^(NSString * title)
     {
         weakSelf.searchWords = title;
         [weakSelf searchKeyWords:title];
     }];

    self.navigationItem.titleView = searchView;
}


-(void)searchKeyWords:(NSString *)keyWords
{
    if ([keyWords isEqualToString:@""] || keyWords == nil)
    {
        alertMessage(@"请输入关键字");
        return;
    }
   
    //不重复插入
    NSArray *arr = [BTHistorySearchM searchWithWhere:@{@"title":keyWords}];
    if (arr.count == 0) {
        BTHistorySearchM *history = [[BTHistorySearchM alloc] init];
        history.title = keyWords;
        NSString *tag =nil ;
        
        switch (self.searchType) {
            case CWQ_historySearchVCType_Course_ShangXueyuan:
                tag = @"商学院";
                break;
            case CWQ_historySearchVCType_Course_Market:
                
                tag = @"市场";
                break;
            case CWQ_historySearchVCType_Course_Sale_all:
            case CWQ_historySearchVCType_Course_FlagSale:
                tag = @"销售";
                break;
            case CWQ_historySearchVCType_Topic:
                tag = @"专题";
                break;
            case CWQ_historySearchVCType_Course_Guanli:
            case CWQ_historySearchVCType_Course_FlagGuanli:
                tag = @"管理学院";
                break;
                
            case CWQ_historySearchVCType_Consult:
                tag = @"资讯";
                break;
                
            default:
                break;
        }
        history.tag = tag;
       

        [history saveToDB];

    }
    [self requestDataWithKeyWord:keyWords];
   
   
}

- (void)requestDataWithKeyWord:(NSString *)keyword
{
   
    [self requestMarketCourseList:YES];
}

#pragma mark ----------------tableview代理--------------------------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
   return   self.dataArray.count;
  
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.searchType == CWQ_historySearchVCType_Consult) {
        
            BTConsultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BTConsultCell" forIndexPath:indexPath];
        
            cell.model = self.dataArray[indexPath.row];
            return cell;
    }
    
    
    
    CWQ_courseIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CWQ_courseIntroductionCell" forIndexPath:indexPath];
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }

    if (self.searchType !=CWQ_historySearchVCType_Topic) {
        [cell setCourseModel:self.dataArray[indexPath.row]];
        //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    else{
       [cell setTopicModel:self.dataArray[indexPath.row]];
        
    }
    return cell;

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchType == CWQ_historySearchVCType_Consult) {
        
        [self.tableView registerNib:[UINib nibWithNibName:@"BTConsultCell" bundle:nil] forCellReuseIdentifier:@"BTConsultCell"];
        return   [tableView fd_heightForCellWithIdentifier:@"BTConsultCell" configuration:^(BTConsultCell * cell) {
            BTCosultModel *model = self.dataArray[indexPath.row];
            cell.model = model;
        }];
        

    }
    
    return 110;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchType == CWQ_historySearchVCType_Consult) {
        BTCosultModel *model = self.dataArray[indexPath.row];
        
        BTBaseWebVC *vc =[BTBaseWebVC new];
        NSString *typeStr = nil;
        NSString *url;
        if ([model.type isEqualToString:@"ORDINARY"]) {
            typeStr = kConsultDetail;
              url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,model.id];
        }else if([model.type isEqualToString:@"QUESTION"]){
            typeStr = kQuestionDetai;
            url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,model.questionID];
        }
       
        vc.tagKey  =  @"consult";
        vc.url =url;
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    
    if (self.searchType != CWQ_historySearchVCType_Topic) {
        BTCourseDetailVC *vc =[BTCourseDetailVC new];
        BTCourseModel *model = self.dataArray[indexPath.row];
        vc.courseId = [model.id integerValue];
      
        [self.navigationController pushViewController:vc animated:YES];

    }else{
        BTTopicListModel *model = self.dataArray[indexPath.row];
        BTTopicDetailVC *vc =[BTTopicDetailVC new];
        vc.topicId = [model.id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
      [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [searchView.YCWQSearch resignFirstResponder];
}
//-(BOOL) navigationShouldPopOnBackButton ///在这个方法里写返回按钮的事件处理
//{
//    NSArray *vcArr = [self.navigationController viewControllers];
//    UIViewController *vc = vcArr[vcArr.count - 2];
//    [self.navigationController popToViewController:vc animated:NO];
//    return YES;//返回NO 不会执行
//    
//}
- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


@end
